import 'package:fish_redux/fish_redux.dart';
import 'package:school_safe_teacher/constans/constants.dart';
import 'package:school_safe_teacher/utils/sp_utils.dart';

import 'action.dart';
import 'entity/news_entity.dart';
import 'state.dart';

Reducer<HomePageState> buildReducer() {
  return asReducer(
    <Object, Reducer<HomePageState>>{
      HomePageAction.action: _onAction,
      HomePageAction.success: _onSuccess,
      HomePageAction.complete: _onComplete,


    },
  );
}

HomePageState _onAction(HomePageState state, Action action) {
  final HomePageState newState = state.clone();
  return newState;
}
HomePageState _onComplete(HomePageState state, Action action) {
  final HomePageState newState = state.clone();
  newState.easyRefreshController.finishRefresh();
  newState.easyRefreshController
      .finishLoad(noMore: newState.items.length % Constants.PAGE_SIZE != 0);
  return newState;
}


HomePageState _onSuccess(HomePageState state, Action action) {
  final HomePageState newState = state.clone();
  List<NewsEntity> list = action.payload;
  if (list.length < Constants.PAGE_SIZE) {
    state.easyRefreshController.finishLoad(noMore: true);
  }
  if (newState.page == 1) {
    newState..items = list;
  } else {
    newState.items.addAll(list);
  }
  return newState;
}
